package com.naiterui.ehp.bs.im.service.message.push;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.naiterui.ehp.bp.constants.ImConstants;
import com.naiterui.ehp.bp.support.utils.JsonMapper;
import com.naiterui.ehp.bp.utils.biz.AppJumpProtocol;
import com.naiterui.ehp.bs.im.config.PushConfig;
import com.naiterui.ehp.bs.im.network.protocl.FollowUpFillin;
import com.naiterui.ehp.bs.im.network.protocl.Message;
import com.naiterui.ehp.bs.im.remote.IRemoter;
import com.naiterui.ehp.bs.im.utils.Constants;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;

/**
 * PUSH处理
 */
@Service
public class PushHandler {

    /**
     * LOGGER
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(PushHandler.class);

    /**
     * 远程调用服务
     */
    private final IRemoter remoter;

    /**
     * 消息推送配置
     */
    private final PushConfig pushConfig;

    /**
     * 勿扰模式
     */
    private final DisturbHandler disturbHandler;

    /**
     * 屏蔽患者
     */
    private final ShieldHandler shieldHandler;

    public PushHandler(IRemoter remoter, PushConfig pushConfig, DisturbHandler disturbHandler, ShieldHandler shieldHandler) {
        this.remoter = remoter;
        this.pushConfig = pushConfig;
        this.disturbHandler = disturbHandler;
        this.shieldHandler = shieldHandler;
    }

    /**
     * 向用户推送push消息(offline离线消息)
     */
    public void pushOfflineMsgNotice(String userType, Long userId, Message<?> message) throws Exception {

        boolean isDisturb = disturbHandler.isDisturb(userId);

        // 如果医生开启了勿扰模式
        if (isDisturb) {
            LOGGER.debug("doctor {}  is disturb mode!", userId);
            return;
        }

        boolean isShield = shieldHandler.isShield(userId, message.getFrom().getId());

        // 如果医生屏蔽该病人消息
        if (isShield) {
            LOGGER.debug(" doctor {} is shield patient {} !", userId, message.getFrom().getId());
            return;
        }

        // 推送的消息内容
        String msg = "";

        LOGGER.info("发送消息，消息类型 type {}, 消息内容 {}", message.getType(), pushConfig.getMaxTextMsgPushLength() + "||" + pushConfig.getPushImgMsg() + "||" +
                pushConfig.getPushRadioMsg() + "||" + pushConfig.getPushVideoMsg() + "||" + pushConfig.getPushDrugMsg() + "||" + pushConfig.getPushMedicalRecordMsg() + "||" +
                pushConfig.getPushPaidSessionMsg());
        switch (message.getType()) {

            // 文本消息
            case Constants.MESSAGE_TYPE_TEXT:
                // 消息内容
                /*String content = (String) message.getContent();
                // 消息长度
                int contentLength = content.length();
                // 系统设置的消息push最大发送长度
                int maxTextMsgPushLength = pushConfig.getMaxTextMsgPushLength();
                // 如果消息长度超过限制则进行截取
                content = contentLength > maxTextMsgPushLength ? content.substring(0, maxTextMsgPushLength) : content;
                // 构建push消息
                msg = content;*/
                msg = pushConfig.getPushTextMsg();
                break;

            // 图片消息
            case Constants.MESSAGE_TYPE_MEDIA_IMG:
                msg = pushConfig.getPushImgMsg();
                break;

            // 音频消息
            case Constants.MESSAGE_TYPE_MEDIA_AUDIO:
                msg = pushConfig.getPushRadioMsg();
                break;

            // 视频消息
            case Constants.MESSAGE_TYPE_MEDIA_VIDEO:
                msg = pushConfig.getPushVideoMsg();
                break;

            // 推荐用药
            case Constants.MESSAGE_TYPE_DRUG:
                msg = pushConfig.getPushDrugMsg();
                break;

            case Constants.MESSAGE_TYPE_PATEINTS_MEDICAL_RECORD:
                msg = pushConfig.getPushMedicalRecordMsg();

                break;
            /*case Constants.MESSAGE_TYPE_PAID_CONSULT:
                msg = pushConfig.getPushPaidSessionMsg();
                break;*/
            case Constants.MESSAGE_TYPE_REMIND_PATIENTS_FILL_MEDICAL_RECORD:
                msg = pushConfig.getPushMedicalRecordMsg();
                break;
            case Constants.MESSAGE_TYPE_PATIENTS_LAST_MEDICAL_RECORD:
            case Constants.MESSAGE_TYPE_PATIENTS_SERVICE_EVALUATION:
                return;
            case ImConstants.MESSAGE_TYPE_FOLLOW_UP_FILLIN:
                FollowUpFillin followUpFillin =
                    JSONUtil.toBean(JSONUtil.toJsonStr(message.getContent()), FollowUpFillin.class);
                String content = followUpFillin.getContent();
                Map<String, Object> map = new HashMap<>();
                map.put("followUpId", followUpFillin.getFollowUpId());
                map.put("followUpRecordFormId", followUpFillin.getFollowUpRecordFormId());
                // 发送push消息
                remoter.pushMsg(userId, StrUtil.subBefore(content, "，<a", true), userType,
                    AppJumpProtocol.DR_FOLLOW_UP_FORM_NOTICE.parse(JsonMapper.toJson(map)));
                LOGGER.info("发送push通知消息，参数为 userId {}, msg {}, userType {}", userId, msg, userId);
                // logger
                LOGGER.debug("push message {} to doctor {}", msg, userId);
                return;
            default:
                break;
        }

        //push乱码根源
        //        msg = new String(msg.getBytes(), StandardCharsets.UTF_8);

        // 发送push消息
        remoter.pushMsg(userId, msg, userType, AppJumpProtocol.DR_CHATDETAIL.parse(message.getSession().getSessionId()));
        LOGGER.info("发送push通知消息，参数为 userId {}, msg {}, userType {}", userId, msg, userId);
        // logger
        LOGGER.debug("push message {} to doctor {}", msg, userId);

    }

}
